<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :headers="headers"
      :data="dataObj"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <iframe
        :src="dialogImageUrl"
        frameborder="0"
        style="width: 100%; height: 700px"
      />
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import * as imageConversion from 'image-conversion'

export default {
  name: 'MultiUploadFile',
  props: {
    // 图片属性数组
    value: {
      type: Array,
      default: function() {
        return []
      }
    },
    fileNames: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 5
    },
    // 上传文件类型限制
    fileType: {
      type: String,
      default: 'msword|doc|docx|xls|xlsx|ppt|pptx|pdf|png|jpg|jpeg|gif|bmp'
    },
    uploadUrl: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/api/admin/file/upload'
    },
    viewUrl: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/api/admin/file/view/'
    },
    dataObj: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      headers: {
        Authorization: getToken()
      },
      imgType: 'png|jpg|jpeg|gif|bmp',
      dialogVisible: false,
      dialogImageUrl: null,
      fileList: []
    }
  },
  created() {
    const fileList = []
    for (let i = 0; i < this.value.length; i++) {
      fileList.push({
        url: this.viewUrl + this.value[i],
        id: this.value[i],
        name: this.fileNames[i]
      })
    }
    this.fileList = fileList
  },
  methods: {
    emitInput(fileList) {
      const value = []
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].id)
      }
      this.$emit('input', value)
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.emitInput(fileList)
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    beforeUpload(file) {
      const reg = new RegExp(this.fileType, 'i')
      const validate = reg.test(file.type)
      if (!validate) {
        this.$message.error('仅能上传格式是 ' + this.fileType + '的文件!')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过10MB!')
        return false
      }
      // 图片压缩
      const regImg = new RegExp(this.imgType, 'i')
      const validateImg = regImg.test(file.type)
      if (validateImg) {
        return new Promise((resolve) => {
          // 压缩到200KB,这里的200就是要压缩的大小,可自定义
          imageConversion.compressAccurately(file, 200).then((res) => {
            resolve(res)
          })
        })
      }
    },
    handleUploadSuccess(res, file) {
      const attachment = res.data.attachment
      this.fileList.push({
        url: this.viewUrl + attachment.fileAttachmentId,
        name: file.name,
        id: attachment.fileAttachmentId
      })
      this.emitInput(this.fileList)
    },
    handleExceed(files, fileList) {
      this.$message({
        message:
          '最多只能上传' + this.maxCount + '个文件，请先删除已上传文件后尝试',
        type: 'warning',
        duration: 2000
      })
    }
  }
}
</script>
<style></style>
